import { defineComponent, ref, onMounted, watch, nextTick } from "vue";
import {
  SyncOutlined,
  FileExcelOutlined,
  SearchOutlined,
  InboxOutlined,
} from "@ant-design/icons-vue";
import { message, Modal } from "ant-design-vue";
import styles from "./lTable.module.less";
import Filter from "./filter/filter";
import LIcon from "@/components/public/lIcon/lIcon";
import SearchForm from "./searchForm/searchForm";
import _ from "lodash";
import useNavigator from "@/hooks/useNavigator";
import { analysisAuthAndOr } from "@/auth/checkAuth";
export default defineComponent({
  name: "Ltable",
  props: {
    toolbar: {
      type: Object,
    },
    service: {
      required: true,
    },
    authConfig: {
      type: Object,
    },
    deleteRows: {
      type: Function,
    },
    modelValue: {
      type: Object,
    },
  },
  emits: [
    "blockSelect",
    "searchSelect"
  ],
  setup(props, { slots, expose,emit}) {
    const navigator = useNavigator();
    //分页器已加载
    const pagenationLoad = ref(false);
    // 定义服务
    const $service: any = props.service;
    // 表格数据
    let val: any = props.modelValue;
    // 表格行权限处理
    val.columns = val.columns.filter((x: any) => {
      let bool = true;
      if (x.auth) {
        bool = analysisAuthAndOr(x.auth, props.authConfig);
      } else {
        bool = true;
      }
      return bool;
    });
    // 表格原始数据
    const ori_columns = [...val.columns];
    // 表格筛选条件
    const searchForm = ref({});
    // 表格方法
    //获取表格数据
    const $fetchTableData = async () => {
      val.loading = true;
      try {
        let query = val?.query || [];
        let pageParams: any = {};
        if (val.pagination) {
          pageParams.limit = val.pagination.pageSize;
          pageParams.page = val.pagination.current;
        }
        const res = await $service.getTable({
          ...query,
          ...pageParams,
          ...searchForm.value,
        });
        // 存在分页时数据形式为res.data.data,不分页时为res.data
        if (val.pagination) {
          val.dataSource = res.data?.data || [];
          val.pagination.total = res.data?.total || 1;
        } else {
          val.dataSource = res.data || [];
        }
        nextTick(() => {
          pagenationLoad.value = true;
        });
      } finally {
        val.loading = false;
      }
    };
    // 删除表格行
    const $deleteTableRows = async (rows: any[]) => {
      let del_res = false;
      try {
        await $service.delete(rows);
        message.success("删除成功!");
        del_res = true;
        props.toolbar?.delete?.handler?.();
      } catch (err: any) {}
      if (del_res) {
        await $fetchTableData();
      }
      return del_res;
    };
    // 初始化
    const init = async () => {
      let val: any = props.modelValue;
      val.dataSource = [];
      val.pagination && (val.pagination.current = 1);
      pagenationLoad.value = false;
      await $fetchTableData();
    };
    // 刷新
    const refresh = _.debounce(
      async () => {
        await init();
        props.toolbar?.refresh?.handler?.();
      },
      300,
      { leading: true, trailing: false }
    );
    // 删除多行
    const deleteRows = async () => {
      if (!val.selectedRowKeys || val.selectedRowKeys.length === 0) {
        message.error("未选中任何行!");
        return;
      }
      Modal.confirm({
        title: "提示",
        content: "确认删除?",
        onOk: async () => {
          const del_res = await $deleteTableRows(val.selectedRowKeys);
        },
      });
    };
    // 监听分页器
    props.modelValue?.pagination &&
      watch(
        props.modelValue?.pagination,
        (nv) => {
          if (!pagenationLoad.value) {
            return;
          }
          $fetchTableData();
        },
        {
          immediate: false,
          deep: true,
        }
      );
    let ToolbarLeft = () => (
      <div class={styles["toolbar-left"]}>
        {props.toolbar?.left?.map((x: any) => {
          if (x) {
            if (typeof x === "string") {
              // 无权限去除
              if (
                !props.toolbar?.[x]?.auth ||
                analysisAuthAndOr(props.toolbar?.[x]?.auth, props.authConfig)
              ) {
                switch (x) {
                  case "refresh":
                    return (
                      <a-button
                        title="刷新"
                        v-slots={{
                          icon: () => <SyncOutlined />,
                        }}
                        onClick={() => {
                          refresh();
                        }}
                      ></a-button>
                    );
                  case "add":
                    return (
                      <a-button
                        type="primary"
                        v-slots={{
                          icon: () => <LIcon type="icon-add" color="white" />,
                        }}
                        onClick={() => {
                          props.toolbar?.add?.handler?.();
                        }}
                      >
                        添加
                      </a-button>
                    );
                    case "groupAdd":
                      return (
                        <a-button
                          type="primary"
                          v-slots={{
                            icon: () => <LIcon type="icon-add" color="white" />,
                          }}
                          onClick={() => {
                            props.toolbar?.groupAdd?.handler?.();
                          }}
                        >
                          录入团单
                        </a-button>
                      );
                  case "upload":
                    return (
                      <a-button
                        type="primary"
                        v-slots={{
                          icon: () => <InboxOutlined />,
                        }}
                        onClick={() => {
                          props.toolbar?.upload?.handler?.();
                        }}
                      >
                       批量修改
                      </a-button>
                    );
                  case "modify":
                    return (
                      <a-button
                        type="primary"
                        v-slots={{
                          icon: () => <InboxOutlined />,
                        }}
                        onClick={() => {
                          props.toolbar?.modify?.handler?.();
                        }}
                      >
                        修改
                      </a-button>
                    );
                  case "deleteUpload":
                    return (
                      <a-button
                        type="primary"
                        v-slots={{
                          icon: () => <InboxOutlined />,
                        }}
                        onClick={() => {
                          props.toolbar?.deleteUpload?.handler?.();
                        }}
                      >
                        删除
                      </a-button>
                    );
                  case "delete":
                    return (
                      <a-button
                        danger
                        type="primary"
                        v-slots={{
                          icon: () => (
                            <LIcon type="icon-delete" color="white" />
                          ),
                        }}
                        onClick={() => {
                          deleteRows();
                        }}
                      >
                        删除
                      </a-button>
                    );
                  case "output":
                    return (
                      <a-button
                        class={styles["output-btn"]}
                        type="primary"
                        v-slots={{
                          icon: () => <FileExcelOutlined />,
                        }}
                        onClick={() => {
                          props.toolbar?.output?.handler?.(searchForm.value);
                        }}
                      >
                        导出
                      </a-button>
                    );
                    case "batch":
                      return (
                        <a-button
                          type="primary"
                          v-slots={{
                            icon: () => <LIcon type="icon-add" color="white" />,
                          }}
                          onClick={() => {
                            props.toolbar?.batch?.handler?.();
                          }}
                        >
                          批量承保
                        </a-button>
                      );
                      case "export":
                        return (
                          <a-button
                            type="primary"
                            v-slots={{
                              icon: () => <FileExcelOutlined />,
                            }}
                            onClick={() => {
                              props.toolbar?.export?.handler?.();
                            }}
                          >
                            承保导出
                          </a-button>
                        );
                  case "close":
                    return (
                      <a-button
                        onClick={() => {
                          navigator.back();
                        }}
                      >
                        关闭
                      </a-button>
                    );
                }
              }
            } else {
              // 无权限去除
              if (!x.auth || analysisAuthAndOr(x.auth, props.authConfig)) {
                return x.el(this);
              }
            }
          }
        })}
      </div>
    );
    // 过滤列
    const filterVisible = ref(false);
    if (props?.toolbar?.right?.some((x: any) => x === "filter")) {
      document
        .getElementsByTagName("body")[0]
        .addEventListener("click", (e) => {
          filterVisible.value = false;
        });
    }
    const filterColumns = (e: any) => {
      const updateTree = (arr: any[]) => {
        arr = arr.filter((x: any) => {
          let itm =
            x.dataIndex instanceof Array ? x.dataIndex.join(".") : x.dataIndex;
          return e.includes(itm);
        });
        arr.forEach(
          (x) =>
            x.children &&
            x.children.length > 0 &&
            (x.children = updateTree(x.children))
        );
        return arr;
      };
      val.columns = _.cloneDeep(ori_columns);
      val.columns = updateTree(val.columns);
      props.toolbar?.filter?.handler?.();
    };
    const searchFormShow = ref(false);
    // 搜索
    const doSearch = () => {
      searchFormShow.value = !searchFormShow.value;
    };
    const searchConfirm = (e: any) => {
      searchForm.value = e;

      init();
    };
    let ToolbarRight = () => (
      <div class={styles["toolbar-right"]}>
        {props.toolbar?.right?.map((x: any) => {
          if (typeof x === "string") {
            // 无权限去除
            if (
              !props.toolbar?.[x]?.auth ||
              analysisAuthAndOr(props.toolbar?.[x]?.auth, props.authConfig)
            ) {
              switch (x) {
                case "filter":
                  return (
                    <div class={styles["filter-btn"]}>
                      <a-button
                        title="列设置"
                        onClick={(e: any) => {
                          e.stopPropagation();
                          filterVisible.value = !filterVisible.value;
                        }}
                        v-slots={{
                          icon: () => <LIcon type="icon-shaixuanlie" />,
                        }}
                      ></a-button>
                      <Filter
                        style={{
                          display: filterVisible.value ? "flex" : "none",
                        }}
                        columns={_.cloneDeep(props?.modelValue?.columns).map(
                          (x: any) => {
                            x.dataIndex instanceof Array &&
                              (x.dataIndex = x.dataIndex.join("."));
                            return x;
                          }
                        )}
                        onChange={(e: any) => {
                          filterColumns(e);
                        }}
                      />
                    </div>
                  );
                case "output":
                  return (
                    <a-button
                      title="导出excel"
                      v-slots={{
                        icon: () => <FileExcelOutlined />,
                      }}
                      onClick={() => {}}
                    ></a-button>
                  );
                case "search":
                  return (
                    <a-button
                      title="搜索"
                      v-slots={{
                        icon: () => <SearchOutlined />,
                      }}
                      onClick={() => {
                        doSearch();
                      }}
                    ></a-button>
                  );
              }
            }
          } else {
            // 无权限去除
            if (!x.auth || analysisAuthAndOr(x.auth, props.authConfig)) {
              return x.el(this);
            }
          }
        })}
      </div>
    );
    
    onMounted(() => {
      init();
    });
    // 抛出服务方法
    expose({
      $fetchTableData,
      $deleteTableRows,
    });
    const Components = () => (
      <>
        <div class={styles["table-container"]}>
          {Object.keys(val?.searchForm || {}).length > 0 && (
            <SearchForm
              authConfig={props.authConfig}
              fields={val.searchForm}
              style={searchFormShow.value ? {} : { display: "none" }}
              onConfirm={(e: any) => {
                searchConfirm(e);
              }}
              onSearchSelect={(e:any)=>{
                 emit("searchSelect",e);
              }}
              onBlockSelect={(e:any)=>{
                 emit("blockSelect",e);
              }}
            />
          )}
          {(props?.toolbar?.left?.length > 0 ||
            props?.toolbar?.right?.length > 0) && (
            <div class={styles.toolbar}>
              <ToolbarLeft></ToolbarLeft>
              <ToolbarRight></ToolbarRight>
            </div>
          )}
          {slots.default && slots.default()}
        </div>
      </>
    );
    return {
      Components,
    };
  },
  render() {
    return <this.Components />;
  },
});
